package com.sphd.emanu.activity.gooddetails;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.sphd.emanu.R;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.goods.Category;
import com.sphd.emanu.pojo.goods.Commodity;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.PermissionConfig;
import com.sphd.emanu.utils.imageselect.PicassoImageLoader;
import com.squareup.picasso.Picasso;
import com.wzutils.BigDisMailUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 商品详情
 * 此界面为 编辑 新增 展示 三界面合一
 *
 * @Author Hu
 * @Time 2017/5/10 -- 11:56.
 * @Email 87683202@qq.com
 */
public class GooddetailsActivity extends MVPBaseActivity<GooddetailsContract.View, GooddetailsPresenter> implements GooddetailsContract.View {


    @BindView(R.id.btn_edit)
    TextView btnEdit;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.edit_good_no)
    EditText editGoodNo;
    @BindView(R.id.edit_good_name)
    EditText editGoodName;
    @BindView(R.id.edit_good_classify)
    TextView editGoodClassify;
    @BindView(R.id.layout_classify)
    LinearLayout layoutClassify;
    @BindView(R.id.food_image)
    ImageView foodImage;
    @BindView(R.id.edit_good_kg)
    EditText editGoodKg;
    @BindView(R.id.edit_good_price)
    EditText editGoodPrice;

    @BindView(R.id.is_dis_t)
    ToggleButton isDisT;

    @BindView(R.id.is_added_t)
    ToggleButton isAddedT;
    @BindView(R.id.btn_save)
    Button btnSave;
    private static final String TAG = "GooddetailsActivity";
    private List<String> path = new ArrayList<>();

    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;

    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    Intent intent;
    Bundle bundle;
    int flag;//0为新增 1为修改
    AndroidNextInputs inputs;
    List<Category> tMtCategoryList;
    int pos = 0;
    User userEntity;
    Commodity goodsEntity;
    List<Moudle> moudles;
    boolean isCanDo=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gooddetails);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        flag = bundle.getInt(Constant.FLAG);
        userEntity = (User) bundle.getSerializable(Constant.USER_ENTITY);
        moudles= (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo=isCanDo(moudles, PermissionConfig.MENU_FOOD_1);
        if (isCanDo){
            btnEdit.setVisibility(View.VISIBLE);
        }

        tMtCategoryList = (List<Category>) bundle.getSerializable(Constant.LIST_CATEGORY);
        pos = bundle.getInt(Constant.POS);
        inputs = new AndroidNextInputs();
        inputs.add(editGoodName, StaticScheme.NotBlank().msgOnFail("商品名称不能为空"));
        inputs.add(editGoodKg, StaticScheme.NotBlank().msgOnFail("商品重量不能为空"), StaticScheme.Numeric().msgOnFail("请输入数字"));
        inputs.add(editGoodPrice, StaticScheme.NotBlank().msgOnFail("价格不能为空"), StaticScheme.Numeric().msgOnFail("请输入数字"));
        initGallery();
        init();
        initUi();
        editGoodClassify.setText(tMtCategoryList.get(pos).getName());
    }

    private void initUi() {
        if (flag == 0) {
            setTitleBar(toolbar, "新增商品");
            editeView();
        } else {
            setTitleBar(toolbar, "商品详情");
            goodsEntity = (Commodity) bundle.getSerializable(Constant.COMMODITY);
            setVeiwEnabled(foodImage, false);
            editGoodNo.setText(String.valueOf(goodsEntity.getId()));
            editGoodName.setText(goodsEntity.getName());
            setImageNet(foodImage, goodsEntity.getImages().getThumbnail());
            editGoodKg.setText(BigDisMailUtils.turnTrim(goodsEntity.getNetWeight(), Constant.POINT));
            editGoodPrice.setText(BigDisMailUtils.turnTrim(goodsEntity.getUnitPrice(), Constant.POINT));
            isDisT.setChecked(goodsEntity.getDiscountable());
            isAddedT.setChecked(goodsEntity.getShelved());
        }

    }


    private void initEvent() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @OnClick({R.id.btn_edit, R.id.layout_classify, R.id.food_image, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_edit:
                editeView();
                break;
            case R.id.layout_classify:
                showList();
                break;
            case R.id.food_image:
                initPermissions();
                break;
            case R.id.btn_save:
                comit();
                break;
        }
    }

    private void comit() {

        if (inputs.test()) {
            //提交信息
            if (flag == 0) {
                if (path.size() != 0){
                    mPresenter.addOrEditeFood(editGoodName.getText().toString().trim(), tMtCategoryList.get(pos).
                                    getId(), prepareFilePart("image" , path.size() != 0 ? path.get(0) : "")
                            , editGoodKg.getText().toString().trim(), editGoodPrice.getText().toString().trim()
                            , isDisT.isChecked(), isAddedT.isChecked(), userEntity.getOid());
                }else {
                    mPresenter.addCommodityNoImage(editGoodName.getText().toString().trim(), tMtCategoryList.get(pos).
                                    getId(), editGoodKg.getText().toString().trim(), editGoodPrice.getText().toString().trim()
                            , isDisT.isChecked(), isAddedT.isChecked(), userEntity.getOid());
                }

            } else {

                if (path.size() != 0){
                    mPresenter.updateCommodity(goodsEntity.getId(), editGoodName.getText().toString().trim(),
                            tMtCategoryList.get(pos).getId(), prepareFilePart("image"
                                    , path.size() != 0 ? path.get(0) : "")
                            , editGoodKg.getText().toString().trim(), editGoodPrice.getText().toString().trim()
                            , isDisT.isChecked(), isAddedT.isChecked(), userEntity.getOid());
                }else {
                    mPresenter.updateCommodityNoImage(goodsEntity.getId(), editGoodName.getText().toString().trim(),
                            tMtCategoryList.get(pos).getId()
                            , editGoodKg.getText().toString().trim(), editGoodPrice.getText().toString().trim()
                            , isDisT.isChecked(), isAddedT.isChecked(), userEntity.getOid());
                }

            }
            showProgressDialog();

        } else {
            toast("请按提示补全信息。");
        }
    }

    /**
     * 编辑Ui
     */
    private void editeView() {
        //隐藏编辑按钮 ,显示保存按钮
        setGONE(btnEdit);
        setVISIBLE(btnSave);
        setVeiwEnabled(editGoodName, true);
        setVeiwEnabled(editGoodClassify, true);
        setVeiwEnabled(foodImage, true);
        setVeiwEnabled(editGoodKg, true);
        setVeiwEnabled(editGoodPrice, true);
        setVeiwEnabled(isDisT, true);
        setVeiwEnabled(isAddedT, true);
    }

    @Override
    public void setRes(int res) {
        dissProgressDialog();
        if (res==1){
            toast("操作成功");
            setResult(Constant.REQUEST_CODE);
            finish();
        }else {
            toast("操作失败，请重试。");
        }
    }

    private void showList() {
        final String[] strings = new String[tMtCategoryList.size()];
        for (int i = 0; i < tMtCategoryList.size(); i++) {
            strings[i] = tMtCategoryList.get(i).getName();
        }

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("请选择分类？").
                setIcon(R.drawable.ic_launcher)
                .setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editGoodClassify.setText(strings[which]);
                        pos = which;
                    }
                }).setNegativeButton("取消", null).
                        create();
        alertDialog.show();
    }

    /**
     * 初始化配置
     */
    private void init() {
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.sphd.emanu.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(true)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(true, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();

    }

    /**
     * 跳转返回的数据
     */
    private void initGallery() {
        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Log.i(TAG, "onStart: 开启");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                Log.e(TAG, "onSuccess: 返回数据");
                path.clear();
                for (String s : photoList) {
                    Log.e(TAG + "->>>", s);
                    path.add(s);
                }
                if (path.size() != 0)
                    setImage(foodImage, "file://" + path.get(0));

            }

            @Override
            public void onCancel() {
                toast("取消");
                Log.e(TAG, "onCancel: 取消");
            }

            @Override
            public void onFinish() {
                Log.e(TAG, "onFinish: 结束");
            }

            @Override
            public void onError() {
                toast("出错了，请重试！");
                Log.e(TAG, "onError: 出错");
            }
        };

    }

    // 授权管理
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "需要授权 ");
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Log.e(TAG, "拒绝过了");
                toast("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                Log.e(TAG, "进行授权");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            Log.e(TAG, "不需要授权 ");
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "同意授权");
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
            } else {
                Log.e(TAG, "拒绝授权");
            }
        }
    }

}
